import 'dart:io';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:dio/dio.dart';

class FileUploadInfo {
  File file;
  bool isUploading;
  bool isCancelled;
  CancelToken cancelToken;
  Response? response;

  FileUploadInfo({
    required this.file,
    this.isUploading = false,
    this.isCancelled = false,
    required this.cancelToken,
    this.response,
  });
}

class LYFileListView extends StatefulWidget {
  const LYFileListView({super.key});
  @override
  State<LYFileListView> createState() => _LYFileListViewState();
}

class _LYFileListViewState extends State<LYFileListView> {
  List<FileUploadInfo> selectedFiles = [];

  Future<void> selectFiles() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      allowMultiple: true,
      type: FileType.any,
    );

    if (result != null) {
      setState(() {
        selectedFiles.addAll(
          result.paths.map((path) {
            return FileUploadInfo(
              file: File(path!),
              cancelToken: CancelToken(),
            );
          }).toList(),
        );
      });
    }
  }

  Future<void> uploadFile(FileUploadInfo fileInfo) async {
    setState(() {
      fileInfo.isUploading = true;
    });

    try {
      var dio = Dio();
      var formData = FormData.fromMap({
        'files': await MultipartFile.fromFile(fileInfo.file.path),
      });

      var response = await dio.post(
        'https://your-api-url.com/upload',
        data: formData,
        cancelToken: fileInfo.cancelToken,
      );

      if (!fileInfo.isCancelled) {
        fileInfo.response = response;
        if (response.statusCode == 200) {
          print('文件上传成功: ${fileInfo.file.path}');
        } else {
          print('文件上传失败，状态码: ${response.statusCode}, 文件: ${fileInfo.file.path}');
        }
      }
    } on DioException catch (e) {
      if (CancelToken.isCancel(e)) {
        print('文件上传已取消: ${fileInfo.file.path}');
      } else if (!fileInfo.isCancelled) {
        print('上传过程中出现错误: $e, 文件: ${fileInfo.file.path}');
      }
    } finally {
      setState(() {
        fileInfo.isUploading = false;
      });
    }
  }

  void cancelUpload(FileUploadInfo fileInfo) {
    setState(() {
      fileInfo.isCancelled = true;
    });
    if (!fileInfo.cancelToken.isCancelled) {
      fileInfo.cancelToken.cancel();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('多文件上传'),
      ),
      body: Column(
        children: [
          ElevatedButton(
            onPressed: selectFiles,
            child: const Text('选择文件'),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: selectedFiles.length,
              itemBuilder: (context, index) {
                var fileInfo = selectedFiles[index];
                return ListTile(
                  title: Text(fileInfo.file.path.split('/').last),
                  subtitle: fileInfo.isUploading
                      ? const Text('上传中...')
                      : fileInfo.response != null
                          ? Text('上传状态: ${fileInfo.response!.statusCode}')
                          : null,
                  trailing: fileInfo.isUploading
                      ? IconButton(
                          icon: const Icon(Icons.cancel),
                          onPressed: () => cancelUpload(fileInfo),
                        )
                      : ElevatedButton(
                          onPressed: () => uploadFile(fileInfo),
                          child: const Text('上传'),
                        ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}
